package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Message;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-25
 */
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    MessageService messageService;

    /**
     * 添加新的信息
     *
     * @param message
     * @return
     */
    @PostMapping("/add")
    public R addMessage(@RequestBody Message message) {
        int result = messageService.insert(message);
        if (result == 1) {
            return R.ok().data("msg", "添加成功");
        }
        return R.error().data("msg", "添加失败");
    }

    /**
     * 删除信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteMessage(@PathVariable("id") Integer id) {
        int result = messageService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");
    }

    /**
     * 修改信息
     *
     * @param id
     * @param message
     * @return
     */
    @PutMapping("/update/{id}")
    public R updateMessage(@PathVariable("id") Integer id, @RequestBody Message message) {
        message.setId(id);
        int result = messageService.update(message);
        if (result == 1) {
            return R.ok().data("msg", "修改成功");
        }
        return R.error().data("msg", "修改失败");
    }

    /**
     * 根据ID查找信息
     *
     * @param id
     * @return
     */
    @GetMapping("/selsectById/{id}")
    public R seleceById(@PathVariable("id") Integer id) {
        List<Message> messageList = messageService.selectById(id);
        if (!messageList.isEmpty())
            return R.ok().data("message", messageList);
        return R.error().data("msg", "查找不到信息，请输入正确的ID");
    }

    /**
     * 分页查询
     *
     * @param query
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/search")
    public R searchUsers(@RequestParam(value = "category", required = false) String category,
                         @RequestParam(value = "userId", required = false) Integer userId,
                         @RequestParam("pagenum") int pageNum,
                         @RequestParam("pagesize") int pageSize) {
        // 根据查询关键字、当前页数和每页显示的数据条数进行查询操作
        try {
            IPage<Message> messageIPage = messageService.searchMessage(userId, category, pageNum, pageSize);
            return R.ok().data("message", messageIPage.getRecords()).data("total", messageIPage.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

}

